﻿/**
 * 图片轮换插件（jQuery plugin）
 * @author Rox <rox@taomee.com>
 */
(function($) {
    $.extend({
        hide_image_switcher: function() {
            $('.left_column .tv .show *').hide();
            window.hide_image_switcher = true;
        },
        resume_image_switcher: function() {
            $('.left_column .tv .show *').show();
            window.hide_image_switcher = false;
        }
    });

    $.fn.image_switcher = function(params) {
        var wrapper = this;
        wrapper.current_index = -1;	// 当前图片 index
        wrapper.timer         = null;	// 自动轮换定时器

        var default_params = {
            'images': [],
            'texts': [],
            'text_prefix': [
                '法兰克国王隆重推荐：',
                '爱丽丝王后刚玩过：',
                '将军杰瑞觉得这个游戏还不错：',
                '小丑嘻嘻相信你一定会喜欢：'
            ],
            'links': [],								// 图片链接
            'width': 360,
            'height': 240,
            '#content': '.show',						// css selectors
            '#text': '.text',
            '#handler': '.subbar ul > li',
            '.handler_on': 'on',						// 导航按钮元素对应的当前图片显示时的 css 类
            'autoswitch': true,							// 是否自动开始轮换 默认：是
            'clicktoswitch': true,						// 点击导航按钮元素的行为：是否是切换到对应的图片 默认：否
            'interval': 5,								// 自动切换的间隔时间 单位：秒
            'callback': null							// 切换完成之后调用的函数，function(current_index) { ... }
        };

        params = $.extend(default_params, params);

        if ( !params.images || !params.texts || params.images.length < 1 || params.texts.length < 1 ) {
            return this;
        }

        // utility function, generate a random str
        var randomString = function() {
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
            var string_length = 8;
            var randomstring = '';
            for (var i=0; i<string_length; i++) {
                var rnum = Math.floor(Math.random() * chars.length);
                randomstring += chars.substring(rnum, rnum+1);
            }
            return randomstring;
        };

        var elm_content  = $(params['#content'], this);
        var elm_text     = $(params['#text'], this);
        var elm_handlers = $(params['#handler'], this);

        if ( params.text_prefix && $(params.text_prefix).length > 0 )
        {
            $(params.texts).each(function(index, item) {
                if ( !params.text_prefix[index] ) return;
                old_text = params.texts[index];
                params.texts[index] = params.texts[index].replace(/>([^<>]+)</, ">" + params.text_prefix[index] + "$1<");

                if ( params.texts[index]==old_text )
                {
                    params.texts[index] = params.text_prefix[index] + params.texts[index];
                }
            });
        }

        var ph_container = $('<div></div>').hide().appendTo(document.body);
        var elm_images = [];
        $(params.images).each(function(index, item) {
            var random_id = randomString();
            var elm = $('<div></div>').attr('id', random_id).appendTo(ph_container);

            if ( typeof item == 'string' )
            {
                if ( item.match(/swf/) )
                {
                    // wait till elm is ready
                    var check_timer = window.setInterval(function() {
                        if ( document.getElementById(random_id) )
                        {
                            window.clearInterval(check_timer);
                            // requires swfobject
                            swfobject.embedSWF(
                                '/html/flash/player/DaWanGuoSwfLoader.swf',
                                random_id,
                                params.width.toString(),
                                params.height.toString(),
                                "9.0.0",
                                "/html/flash/expressInstall.swf",
                                {
                                    link: params.links[index],
                                    swfUrl: item
                                },
                                {
                                    quality: 'high',
                                    wmode: 'window'
                                },
                                null,
                                function() {
                                    elm = $('#' + random_id);
                                    elm_images.push(elm);
                                }
                            );
                        }
                    }, 10);
                }
                else
                {
                    var img = $('<img></img>').attr('src', item);
                    var links = params.links;
                    if ( links && links[index] )
                    {
                        $('<a></a>').attr('href', links[index])
                                    .attr('target', '_blank')
                                    .append(img)
                                    .appendTo(elm);
                    }
                    else
                    {
                        img.appendTo(elm);
                    }
                    if ( params.width && params.height ) {
                        img.attr('width', params.width)
                           .attr('height', params.height);
                    }
                    elm_images.push(elm);
                }
            }
            else
            {
                $(item).appendTo(elm);
                elm.css('position', 'absolute');
                elm_images.push(elm);
            }
        });

        // 切换至……（主要功能函数）
        var switch_to = function(index) {
            if ( !elm_images || elm_images.length <= 0 ) return false;
            // circle back
            if ( !index || index >= params.images.length) {
                index = 0;
            } else if ( index < 0 ) {
                index = params.images.length;
            }

            if ( wrapper.current_index == index ) {
                return wrapper;
            }

            $(elm_content.children()).appendTo(ph_container);
            elm_content.empty();

            $(elm_images[index]).appendTo(elm_content).show();

            if ( window.hide_image_switcher )
            {
                $(elm_images[index]).hide();
            }
            else
            {
                $(elm_images[index]).show();
            }
            // set current text
            elm_text.html(params.texts[index]);
            // set handler on/off status
            $.each(elm_handlers, function(i, item) {
                if ( index == i) {
                    $(item).addClass(params['.handler_on']);
                } else {
                    $(item).removeClass(params['.handler_on']);
                }
            });
            // update current index
            wrapper.current_index = index;
            // call user defined callback function
            if ( params.callback && typeof params.callback == 'function' ) {
                params.callback(index);
            }
            return wrapper;
        };

        // 切换到第一张
        switch_to(0);
        // 自动切换
        if ( params.autoswitch ) {
            var autoswitch_func = function() {
                wrapper.timer = window.setInterval(function() {
                    switch_to(wrapper.current_index + 1);
                }, params.interval*1000);
            };
            autoswitch_func();
        }
        // 点击切换
        if ( params.clicktoswitch ) {
            $.each(elm_handlers, function(index, item) {
                $(item).click(function(e) {
                    if ( wrapper.timer ) {
                        window.clearInterval(wrapper.timer);
                    }
                    e.preventDefault();
                    e.stopPropagation();
                    if ( index < 0 || index >= params.images.length  ) return;
                    switch_to(index);
                    if ( autoswitch_func ) {
                        autoswitch_func();
                    }
                });
            });
        }
    };
})(jQuery);
